package com.ruoyi.shop.service.impl;

import java.util.Date;
import java.util.List;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.shop.domain.ShopUser;
import com.ruoyi.shop.service.IShopUserService;
import com.ruoyi.shop.vo.WxInfoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.shop.mapper.ShopUserOpenidMapper;
import com.ruoyi.shop.domain.ShopUserOpenid;
import com.ruoyi.shop.service.IShopUserOpenidService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 账号绑定信息Service业务层处理
 * 
 * @author Alan Zhang
 * @date 2021-09-14
 */
@Service
public class ShopUserOpenidServiceImpl implements IShopUserOpenidService 
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ShopUserOpenidMapper shopUserOpenidMapper;
    @Autowired
    private IShopUserService shopUserService;

    /**
     * 查询账号绑定信息
     * 
     * @param id 账号绑定信息主键
     * @return 账号绑定信息
     */
    @Override
    public ShopUserOpenid selectShopUserOpenidById(Long id)
    {
        return shopUserOpenidMapper.selectShopUserOpenidById(id);
    }

    /**
     * 查询账号绑定信息列表
     * 
     * @param shopUserOpenid 账号绑定信息
     * @return 账号绑定信息
     */
    @Override
    public List<ShopUserOpenid> selectShopUserOpenidList(ShopUserOpenid shopUserOpenid)
    {
        return shopUserOpenidMapper.selectShopUserOpenidList(shopUserOpenid);
    }

    /**
     * 新增账号绑定信息
     * 
     * @param shopUserOpenid 账号绑定信息
     * @return 结果
     */
    @Override
    public int insertShopUserOpenid(ShopUserOpenid shopUserOpenid)
    {
        shopUserOpenid.setCreateTime(DateUtils.getNowDate());
        return shopUserOpenidMapper.insertShopUserOpenid(shopUserOpenid);
    }

    /**
     * 修改账号绑定信息
     * 
     * @param shopUserOpenid 账号绑定信息
     * @return 结果
     */
    @Override
    public int updateShopUserOpenid(ShopUserOpenid shopUserOpenid)
    {
        shopUserOpenid.setUpdateTime(DateUtils.getNowDate());
        return shopUserOpenidMapper.updateShopUserOpenid(shopUserOpenid);
    }

    /**
     * 批量删除账号绑定信息
     * 
     * @param ids 需要删除的账号绑定信息主键
     * @return 结果
     */
    @Override
    public int deleteShopUserOpenidByIds(String ids)
    {
        return shopUserOpenidMapper.deleteShopUserOpenidByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除账号绑定信息信息
     * 
     * @param id 账号绑定信息主键
     * @return 结果
     */
    @Override
    public int deleteShopUserOpenidById(Long id)
    {
        return shopUserOpenidMapper.deleteShopUserOpenidById(id);
    }


    /**
     * 查询 账号绑定信息
     * @param sessionKey
     * @return
     */
    @Override
    public ShopUserOpenid selectShopUserOpenidBySessionKey(String sessionKey){
        return shopUserOpenidMapper.selectShopUserOpenidBySessionKey(sessionKey);
    }

    /**
     * 查询 账号绑定信息
     * @param userId
     * @return
     */
    public ShopUserOpenid selectShopUserOpenidByUserId(Long userId){
        return shopUserOpenidMapper.selectShopUserOpenidByUserId(userId);
    }

    /**
     * 创建用户
     * @param wxInfo
     * @param wxMaJscode2SessionResult
     * @return
     */
    @Transactional
    @Override
    public AjaxResult createUser(WxInfoVo wxInfo, WxMaJscode2SessionResult wxMaJscode2SessionResult){
        ShopUserOpenid param = new ShopUserOpenid();
        param.setValue(wxMaJscode2SessionResult.getOpenid());
        List<ShopUserOpenid> userOpenidList = selectShopUserOpenidList(param);

        logger.info("sessionKey:{}",wxMaJscode2SessionResult.getSessionKey());

        if(userOpenidList.size() == 0){
            ShopUserOpenid userOpenid = new ShopUserOpenid();
            userOpenid.setSessionKey(wxMaJscode2SessionResult.getSessionKey());
            userOpenid.setValue(wxMaJscode2SessionResult.getOpenid());
            userOpenid.setType("wechat");
            userOpenid.setNickname(wxInfo.getNickname());
            userOpenid.setAvatar(wxInfo.getAvatar());

            ShopUser shopUser = createShopUser(wxInfo);

            userOpenid.setUserId(shopUser.getId());
            int rows = insertShopUserOpenid(userOpenid);
            if(rows>0){
                return AjaxResult.success("注册成功").put("token", userOpenid.getSessionKey());
            } else {
                return AjaxResult.error("微信用户创建失败");
            }
        } else if(userOpenidList.size() == 1){
            ShopUserOpenid shopUserOpenid = userOpenidList.get(0);

            boolean flag = false;
            if(!shopUserOpenid.getSessionKey().equals(wxMaJscode2SessionResult.getSessionKey())) {
                shopUserOpenid.setSessionKey(wxMaJscode2SessionResult.getSessionKey());
                shopUserOpenid.setNickname(wxInfo.getNickname());
                shopUserOpenid.setAvatar(wxInfo.getAvatar());
                flag = true;
            }
            if(shopUserOpenid.getUserId() == null){
                ShopUser shopUser = createShopUser(wxInfo);
                shopUserOpenid.setUserId(shopUser.getId());
                flag = true;
            }

            if(flag) {
                updateShopUserOpenid(shopUserOpenid);
            }
            return AjaxResult.success().put("token", shopUserOpenid.getSessionKey());
        } else {

            return AjaxResult.error("错误,多条信息");
        }
    }

    private ShopUser createShopUser(WxInfoVo wxInfo){
        // 创建新用户
        ShopUser shopUser = new ShopUser();
        shopUser.setNickname(wxInfo.getNickname());
        shopUser.setGender(wxInfo.getGender());
        shopUser.setAvatar(wxInfo.getNickname());
        shopUser.setStatus(1);
        shopUser.setCreateSource("微信");
        shopUser.setActivated(new Date());
        shopUser.setLogged(new Date());
        shopUserService.insertShopUser(shopUser);
        logger.info("创建用户==={}", shopUser.getId());
        return shopUser;
    }
}
